package week_eight;

import java.util.ArrayList;
import java.util.List;

public class FindAllAnagramsInString_438 {
    public List<Integer> findAnagrams(String s, String p) {

        int slen = s.length();
        int plen = p.length();

        int[] countP = new int[26];
        for (int i = 0; i < plen; i++) {
            countP[p.charAt(i) - 'a']++;
        }

        List<Integer> ans = new ArrayList<>();

        for (int i = 0; i <= slen - plen; i++) {
            if (isAnagram(s.substring(i, i + plen), countP)) ans.add(i);
        }
        return ans;

    }

    public boolean isAnagram(String s, int[] countP) {
        int[] countS = new int[26];

        for (int i = 0; i < s.length(); i++) {
            countS[s.charAt(i) - 'a']++;
        }

        for (int i = 0; i < 26; i++) {
            if (countP[i] != countS[i]) return false;
        }

        return true;
    }
}
